import json
from random import choice

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class CookiePool(object):
    proxies = None
    # proxies = {"http": "http://127.0.0.1:8888", "https": "http://127.0.0.1:8888"}
    headers = {
        "accept": "application/json",
        "accept-language": "zh-CN",
        "accept-encoding": "gzip",
        "Host": "api.stepn.io"
    }
    account_pwd_ls = [
        {'account': '2226893225', 'pwd': '12345678'},
    ]

    def login(self):
        '''
        获取登录cookie
        '''
        for dic in self.account_pwd_ls:
            account = dic.get('account')
            pwd = dic.get('pwd')
            login_url = f'https://api.stepn.io/run/login?type=3&account={account}%40qq.com&password={pwd}'
            res = requests.get(login_url, headers=self.headers, verify=False, proxies=self.proxies)
            print(res.cookies)
            data = res.json().get("data") or {}
            uid = data.get('uid') or ''
            token = data.get('token') or ''
            all_cookie_str = ''
            for key, value in dict(res.cookies).items():
                all_cookie_str += '{}={}; '.format(key, value)
            yield all_cookie_str

    def get_cookie_str(self):
        '''
        从文件获取cookie，不存在则通过登录获取
        :return:
        '''
        with open('cookie.json', 'r', encoding='utf-8') as f:
            data = f.read()
            if data:
                all_cookie_list = json.loads(data)
            else:
                all_cookie_list = []
        if not all_cookie_list:
            all_cookie_list = []
            for cookie in self.login():
                all_cookie_list.append(cookie)
            with open('cookie.json', 'w', encoding='utf-8') as f:
                json.dump(all_cookie_list, f, ensure_ascii=False, indent=4)
        return choice(all_cookie_list)

    def delete_cookie(self, cookie):
        '''
        删除指定cookie
        '''
        with open('cookie.json', 'r', encoding='utf-8') as f:
            data = f.read()
            if data:
                all_cookie_list = json.loads(data)
            else:
                all_cookie_list = []
        if cookie in all_cookie_list:
            all_cookie_list.remove(cookie)
        with open('cookie.json', 'w', encoding='utf-8') as f:
            json.dump(all_cookie_list, f, ensure_ascii=False, indent=4)
